package com.macro.mall.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.CombinedPmsProduct;
import com.macro.mall.portal.domain.OmsOrderReturnApplyDto;
import com.macro.mall.portal.domain.OmsOrderReturnApplyParam;
import com.macro.mall.portal.dto.OmsReturnApplyDto;
import com.macro.mall.portal.service.OmsPortalOrderReturnApplyService;
import com.macro.mall.portal.service.OmsPromotionService;
import com.macro.mall.portal.service.UmsMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单退货管理Service实现类
 * Created by macro on 2018/10/17.
 */
@Service
public class OmsPortalOrderReturnApplyServiceImpl implements OmsPortalOrderReturnApplyService {
    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private OmsPromotionService omsPromotionService;
    @Autowired
    private UmsMemberReceiveAddressMapper addressMapper;
    @Autowired
    private OmsOrderReturnReasonMapper reasonMapper;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Override
    public int create(OmsOrderReturnApplyParam returnApplyParam) {
        OmsOrderItem orderItem = orderItemMapper.selectByPrimaryKey(returnApplyParam.getOrderItemId());
        OmsOrder omsOrder = this.omsOrderMapper.selectByPrimaryKey(orderItem.getOrderId());
        OmsOrderSettingExample settingExample = new OmsOrderSettingExample();
        OmsOrderSetting omsOrderSetting = orderSettingMapper.selectByExample(settingExample).get(0);
        Integer finishOvertime = omsOrderSetting.getFinishOvertime();
        Date receiveTime = omsOrder.getReceiveTime();
        if (receiveTime != null) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(receiveTime);
            ca.add(Calendar.DATE, finishOvertime);
            Date time = ca.getTime();
            if (time.before(new Date())) {
                return -1;
            }
        }
        //获取售后单类型
        Integer orderType = returnApplyParam.getOrderType();
        if (orderItem != null) {
            OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
            //设置订单id
            returnApply.setOrderId(orderItem.getOrderId());
            //售后单状态为待处理
            returnApply.setReturnStatus(0);
            //售后单类型
            returnApply.setOrderType(returnApplyParam.getOrderType());
            //子订单id
            returnApply.setOrderItemId(orderItem.getId());
            //退货商品id
            returnApply.setProductId(orderItem.getProductId());
            //订单编号
            returnApply.setOrderSn(omsOrder.getOrderSn());
            //申请时间
            returnApply.setCreateTime(new Date());
            //会员用户名
            returnApply.setMemberUsername(omsOrder.getMemberUsername());
            //退款金额
            BigDecimal count = new BigDecimal( orderItem.getProductQuantity());
            returnApply.setReturnAmount(orderItem.getRealAmount().multiply(count));
            //退款/退款人姓名
            returnApply.setReturnName(returnApplyParam.getReturnName());
            //退款人电话
            returnApply.setReturnPhone(returnApplyParam.getReturnPhone());
            //退款人地址
            returnApply.setCompanyAddressId(returnApplyParam.getCompanyAddressId());
            //商品图片
            returnApply.setProductPic(orderItem.getProductPic());
            //商品名称
            returnApply.setProductName(orderItem.getProductName());
            //商品品牌
            returnApply.setProductBrand(orderItem.getProductBrand());
            //商品销售属性：颜色：红色；尺码：xl
            returnApply.setProductAttr(orderItem.getProductAttr());
            //设置凭证图片
            returnApply.setProofPics(returnApplyParam.getProofPics());
            //商品单价
            returnApply.setProductPrice(orderItem.getProductPrice());
            //商品实际支付单价
            returnApply.setProductRealPrice(orderItem.getRealAmount());
            //原因
            returnApply.setReason(returnApplyParam.getReason());
            //描述
            returnApply.setDescription(returnApplyParam.getDescription());
            //门店用户的id
            returnApply.setMemberId(omsOrder.getMemberId());
            //门店用户名
            returnApply.setMemberUserName(orderItem.getMemberUserName());
            //门店id
            returnApply.setStoreId(omsOrder.getUserStoreId());
            //存子订单状态
            returnApply.setOrderItemStatus(orderItem.getStatus());
            //退货数量
            if (returnApplyParam.getProductCount() != null) {
                returnApply.setProductCount(returnApplyParam.getProductCount());
            }else {
                returnApply.setProductCount(orderItem.getProductQuantity());
            }
            if(orderType.equals(0)){
                //子订单状态为退款中
                orderItem.setStatus(6);
            }else if(orderType.equals(1)){
                //子订单状态为退货中
                orderItem.setStatus(5);
            }
            if(orderType.equals(2)){//换货
                returnApply.setReplaceSkuId(returnApplyParam.getReplaceSkuId());
                //子订单状态为退货中
                orderItem.setStatus(5);
                returnApply.setReturnAmount(BigDecimal.ZERO);
            }
            this.orderItemMapper.updateByPrimaryStatus(orderItem);
            returnApply.setOriginSkuId(orderItem.getProductSkuId());
            // 保存
//            Integer status = this.calOrderStatus(omsOrder,returnApply.getOrderItemStatus());
//            omsOrder.setStatus(status);
            this.returnApplyMapper.insert(returnApply);
            this.omsOrderMapper.updateByPrimaryKeySelective(omsOrder);
        } else {
            return 0;
        }
        return 1;
    }


    private Integer calOrderStatus(OmsOrder omsOrder,Integer status) {
        OmsOrderItemExample example = new OmsOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        List<OmsOrderItem> omsOrderItems = this.orderItemMapper.selectByExample(example);
        Integer flag = 0;//退款
        Integer flag1 = 0;//退货

        for (OmsOrderItem orderItem: omsOrderItems) {
            if(orderItem.getStatus().equals(5)){
                flag++;
            }
            if(orderItem.getStatus().equals(6)){
                flag1++;
            }
        }
        if((flag+flag1)==omsOrderItems.size()){
            status = 5;
        }
        if(flag.equals(omsOrderItems.size())){
            status = 5;
        }
        if(flag1.equals(omsOrderItems.size())){
            status = 6;
        }

        return status;
    }

    /**
     * 分页查询售后订单
     *
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public CommonResult<CommonPage<OmsOrderReturnApplyDto>> getList(String productName, Integer pageSize, Integer pageNum) {
        List<OmsOrderReturnApplyDto> result = new ArrayList<>();
        UmsMember currentMember = this.memberService.getCurrentMember();
        PageHelper.startPage(pageNum, pageSize);
        OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
        OmsOrderReturnApplyExample.Criteria criteria = example.createCriteria();
        criteria.andMemberIdEqualTo(currentMember.getId());
        if (productName != null && !"".equals(productName)) {
            criteria.andProductNameEqualTo("%" + productName + "%");
        }
        example.setOrderByClause("create_time desc");
        List<OmsOrderReturnApply> orderReturnApplyList = returnApplyMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(orderReturnApplyList)) {
            for (OmsOrderReturnApply omsOrderReturnApply : orderReturnApplyList){
                OmsOrderReturnApplyDto returnApplyDto = getReturnList(omsOrderReturnApply.getId());
                result.add(returnApplyDto);
            }
        }
        return CommonResult.success(CommonPage.restPage(result));
    }

    /**
     * 根据id查询售后单详情页
     */
    @Override
    public OmsOrderReturnApplyDto getReturnList(Long id) {
        OmsOrderReturnApply omsOrderReturnApply = returnApplyMapper.selectByPrimaryKey(id);
        OmsOrderReturnApplyDto dto = new OmsOrderReturnApplyDto();
        BeanUtils.copyProperties(omsOrderReturnApply,dto);

        OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(omsOrderReturnApply.getOrderItemId());
        //订单类型
        OmsOrder omsOrder = omsOrderMapper.selectByPrimaryKey(omsOrderItem.getOrderId());
        dto.setMainOrderType(omsOrder.getOrderType());
        //地址
        UmsMemberReceiveAddress address = new UmsMemberReceiveAddress();
        if(dto.getCompanyAddressId() != null){
            address = addressMapper.selectByPrimaryKey(dto.getCompanyAddressId());
        }
        dto.setAddress(address);
        Integer type = productMapper.selectByPrimaryKey(omsOrderItem.getProductId()).getType();
        List<CombinedPmsProduct> group = omsPromotionService.getGroup(type, omsOrderItem.getProductSkuId());
        dto.setCombinedPmsProduct(group);
        dto.setProductType(omsOrderItem.getProductType());
        //退款单编号
        dto.setOrderReturnSn(omsOrderItem.getOrderSn() + "-" +omsOrderItem.getId());
        return dto;
    }

    /**
     * 申请换货
     */
    @Override
    public CommonResult exchange(OmsOrderReturnApplyParam orderReturnApply) {
        Boolean flag = true;
        OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
        if (orderReturnApply != null) {
            //换货商品的skuId
            returnApply.setOriginSkuId(orderReturnApply.getOriginSkuId());
            //换出货物的skuid
            returnApply.setReplaceSkuId(orderReturnApply.getReplaceSkuId());
            //换货人姓名
            returnApply.setReturnName(orderReturnApply.getReturnName());
            //换货人电话
            returnApply.setReturnPhone(orderReturnApply.getReturnPhone());
            //收货地址表id
            returnApply.setCompanyAddressId(orderReturnApply.getCompanyAddressId());
            //换货说明
            returnApply.setReason(orderReturnApply.getReason());
            //换货数量
            returnApply.setProductCount(orderReturnApply.getProductCount());
            //凭证图片
            returnApply.setProofPics(orderReturnApply.getProofPics());
            //换货说明
            returnApply.setDescription(orderReturnApply.getDescription());
            //调用方法并保存参数
            OmsOrderReturnApply omsOrderReturnApply = returnApply(orderReturnApply);
            BeanUtils.copyProperties(omsOrderReturnApply,returnApply);
            int count = this.returnApplyMapper.insertSelective(returnApply);
            if(count > 0){
                return CommonResult.success(count);
            }else{
                return CommonResult.failed();
            }
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 查询换货商品的其他sku信息
     */
    @Override
    public CommonResult<List<PmsSkuStock>> getReturnSku(Long orderItemId) {
        OmsOrderItem omsOrderItem = this.orderItemMapper.selectByPrimaryKey(orderItemId);

        PmsSkuStock pmsSkuStock = this.skuStockMapper.selectByPrimaryKey(omsOrderItem.getProductSkuId());

        //根据订单id和商品sku编号查询商品
        PmsSkuStockExample example = new PmsSkuStockExample();
        example.createCriteria()
                .andPriceEqualTo(pmsSkuStock.getPrice())
                .andProductIdEqualTo(pmsSkuStock.getProductId());
        List<PmsSkuStock> pmsSkuStocks = this.skuStockMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(pmsSkuStocks)){
            return CommonResult.success(pmsSkuStocks);
        }else{
            return CommonResult.failed("没有等价的商品信息存在");
        }


    }

    /**
     * 封装售后单获取参数
     */
    private OmsOrderReturnApply returnApply(OmsOrderReturnApplyParam returnApplyParam) {
        OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
        OmsOrderItem orderItem = this.orderItemMapper.selectByPrimaryKey(returnApplyParam.getOrderItemId());
        OmsOrder omsOrder = this.omsOrderMapper.selectByPrimaryKey(orderItem.getOrderId());
        //设置订单id
        returnApply.setOrderId(omsOrder.getId());
        //售后单类型
        returnApply.setOrderType(returnApplyParam.getOrderType());
        //子订单id
        returnApply.setOrderItemId(orderItem.getId());
        //售后单状态为待处理
        returnApply.setReturnStatus(0);
        //退货商品id
        returnApply.setProductId(orderItem.getProductId());
        //订单编号
        returnApply.setOrderSn(omsOrder.getOrderSn());
        //申请时间
        returnApply.setCreateTime(new Date());
        //会员用户名
        returnApply.setMemberUsername(omsOrder.getMemberUsername());
        //商品图片
        returnApply.setProductPic(orderItem.getProductPic());
        //商品名称
        returnApply.setProductName(orderItem.getProductName());
        //商品品牌
        returnApply.setProductBrand(orderItem.getProductBrand());
        //商品销售属性：颜色：红色；尺码：xl
        returnApply.setProductAttr(orderItem.getProductAttr());
        //商品单价
        returnApply.setProductPrice(orderItem.getProductPrice());
        //商品实际支付单价
        returnApply.setProductRealPrice(orderItem.getRealAmount());
        //门店用户的id
        returnApply.setMemberId(orderItem.getMemberId());
        //门店用户名
        returnApply.setMemberUserName(orderItem.getMemberUserName());
        //门店id
        returnApply.setStoreId(orderItem.getStoreId());
        //存子订单状态
        returnApply.setOrderItemStatus(orderItem.getStatus());
        return returnApply;
    }

    /**
     * 撤销售后单
     * @param returnId
     * @param returnId
     * @return
     */
    @Override
    public CommonResult repealReturnApply(Long returnId) {

        OmsOrderReturnApply omsOrderReturnApply = returnApplyMapper.selectByPrimaryKey(returnId);
        //状态改成4已撤销
        omsOrderReturnApply.setReturnStatus(4);
        //查看总订单
//        OmsOrder omsOrder = omsOrderMapper.selectByPrimaryKey(omsOrderReturnApply.getOrderId());
        //获取之前的状态
        OmsOrderItem omsOrderItem = orderItemMapper.selectByPrimaryKey(omsOrderReturnApply.getOrderItemId());
        omsOrderItem.setStatus(omsOrderReturnApply.getOrderItemStatus());
        orderItemMapper.updateByPrimaryStatus(omsOrderItem);
//        Integer orderStatus = calOrderStatus(omsOrder, omsOrderReturnApply.getOrderItemStatus());
//        omsOrder.setStatus(orderStatus);
        int count = returnApplyMapper.updateByPrimaryKeySelective(omsOrderReturnApply);
//        int countOrder = omsOrderMapper.updateByPrimaryKeySelective(omsOrder);
        if (count > 0) {
            return CommonResult.success(count);
        }else {
            return CommonResult.failed();
        }

    }

    @Override
    public CommonResult<List<OmsOrderReturnReason>> getOmsReturnReason() {
        UmsMember currentMember = memberService.getCurrentMember();
        OmsOrderReturnReasonExample example = new OmsOrderReturnReasonExample();
        example.createCriteria().andStoreIdEqualTo(currentMember.getStoreId());
        List<OmsOrderReturnReason> omsReturnReasons = reasonMapper.selectByExample(example);
        return CommonResult.success(omsReturnReasons);
    }


}
